package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    private ProvinceInfoServiceImpl provinceInfoServiceImpl;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        InputStream fileInputStream = file.getInputStream();

        //获取日期
        //方式一：
//        DateTime dateTime = new DateTime();
//        String date = dateTime.toString("yyyy/MM/dd/");

        //方式二：
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));

        //=============================================================


        //生成一个随机文件名，避免文件名重复覆盖已存在的文件
        String fileName = UUID.randomUUID().toString().replace("-", "");

        //获取扩展名
        //方式一 //注意这里要获取原始文件的扩展名
        //String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());


        //=============================================================
        //方式二：
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex > 0){
            extension = originalFilename.substring(lastDotIndex + 1);
        }
        //=============================================================

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                //这个对象就文件对象，包括文件名，文件后缀，文件夹日期
                .object(date + fileName + "." +extension)
                .stream(fileInputStream,file.getSize(),-1)
                .build();

        minioClient.putObject(putObjectArgs);

        return minioProperties.getEndpoint() +  "/" + minioProperties.getBucketName() + "/"+ date+fileName+"."+extension;
    }
}
